package algorithm.linklist;

class Node {
    public int val;
    Node next;

    public Node(int val) {
        this.val = val;
    }

    public Node revert() {
        Node head = this;
        Node pre = null;
        Node next;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

    public Node delByVal(int val) {
        Node head = this;
        // 从左往右找到第一个不用删除的节点
        while (head != null) {
            if (head.val != val) {
                break;
            }
            head = head.next;
        }
        Node pre = head;
        Node cur = head;
        while (cur != null) {
            if (cur.val == val) {
                // 需要删除
                // 肯定不是第一次进来，pre已经记录了之前的节点
                // 目前pre.next=cur
                // 需要删除，因此pre.next = cur.next 跳过cur节点
                pre.next = cur.next;
            } else {
                // 不需要删除
                // 第一次进来肯定不需要删除
                pre = cur;
                // 因此pre还是r
            }
            cur = cur.next;
            // 第一次后cur往后走一步
        }
        return head;
    }

    public static void main(String[] args) {
        Node node = getRandomNode(5, 10);
        LinkUtil.printNode(node);
        node = node.revert();
        LinkUtil.printNode(node);
        node = node.delByVal(5);
        LinkUtil.printNode(node);
    }

    public static Node getRandomNode(int len, int maxVal) {
        Node node = new Node((int) ((Math.random() * maxVal) + 1));
        len--;
        Node next = null;
        while (len != 0) {
            if (node.next == null) {
                node.next = new Node((int) ((Math.random() * maxVal) + 1));
                next = node.next;
            } else {
                next.next = new Node((int) ((Math.random() * maxVal) + 1));
                next = next.next;
            }
            len--;
        }
        return node;
    }

}

